package cn.edu.web;

import cn.edu.pojo.User;
import cn.edu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Davey chan
 */
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService service=new UserService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password= request.getParameter("password");
//        页面输入的验证码
        String checkcode = request.getParameter("checkcode");
//从session拿到生成的验证码
        HttpSession session = request.getSession();
       String  checkCodeGen = (String)session.getAttribute("checkCodeGen");

//
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
//判断输入和生成的验证码是否一样，这里等于忽略了大小写
        if(!checkCodeGen.equalsIgnoreCase(checkcode)){
            //比对不一样，不允许注册
            request.setAttribute("regerr_msg","验证码错误");
//          验证失败还接着跳转到register.jsp
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;//返回，不执行后面的代码
        }

//调用service的注册方法
        boolean flag = service.register(user);
        if(flag){
//            注册成功后返回到登录页面
            request.setAttribute("regerr_msg","注册成功，请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            //找到重复的用户就不能加,给页面返回注册失败的响应
            //存储错误信息到request中
            request.setAttribute("regerr_msg","用户名已存在");
//          登录失败还接着跳转到register.jsp
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
